#!/usr/bin/python3
import struct
import time
from threading import Thread, Event
from queue import Queue
from matplotlib.pyplot import get_plot_commands

import numpy as np
from scipy.signal import hilbert

from usbd import USBDevice
from mcys import ih


class UsRx(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.queue = Queue()
        self.usbd = USBDevice(idVendor=0xffff)
        self.event = Event()
        self.rot = 32

    def rx_pack(self):
        t0 = time.time()
        data = b''
        for i in range(8192//64):
            tmp = self.usbd.read(64)
            if len(tmp) == 4:
                self.rot = struct.unpack('i', tmp)[0]
                self.event.set()
                return self.rx_pack()
            else:
                data += tmp
        return data

    def run(self):
        mul = np.zeros(4096)
        mul[:-25] = np.linspace(0, 3, num=4096-25)
        mul **= 2
        while True:
            data = self.rx_pack()
            arr = np.frombuffer(data, dtype=np.uint16)
            arr = np.clip(arr, 0, 4096)
            arr = arr - arr.mean()  # 去除直流分量
            if arr.shape[0] == 4096:
                x_ = ih.calcx(arr)
                h = hilbert(x_)
                h *= mul
                self.queue.put(np.abs(h))
